﻿using System.Windows;
using System.Windows.Controls;
using LiveTiss.Classes;

namespace LiveTiss.Guias.UserControls
{
    public partial class Int32Picker : UserControl
    {
        public static readonly DependencyProperty SelectedValueProperty = DependencyProperty.Register("SelectedValue",
            typeof(string), typeof(Int32Picker), new PropertyMetadata(SelectedValuePropertyChanged));

        public string SelectedValue
        {
            get { return (string)GetValue(SelectedValueProperty); }
            set { SetValue(SelectedValueProperty, value); }
        }

        public event RoutedPropertyChangedEventHandler<string> SelectedValueChanged;

        private static void SelectedValuePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            Int32Picker myControl = d as Int32Picker;

            if (myControl != null)
            {
                if (e.NewValue != null)
                {
                    myControl.txtInt.Text = e.NewValue.ToString();
                }
                else
                {
                    myControl.txtInt.Text = string.Empty;
                }
            }
            if (myControl.SelectedValueChanged != null && e.OldValue != e.NewValue)
            {
                myControl.SelectedValueChanged(myControl, new RoutedPropertyChangedEventArgs<string>(e.OldValue as string, e.NewValue as string));
            }
        }

        public Int32Picker()
        {
            InitializeComponent();
        }

        private void txtInt_TextChanged(object sender, TextChangedEventArgs e)
        {
            int value = 0;
            txtInt.ClearValidationError();
            if (!int.TryParse(txtInt.Text, out value))
            {
                txtInt.SetValidation("Valor deve ser um inteiro válido");
                txtInt.RaiseValidationError();
            }
            this.SelectedValue = value.ToString();
        }

    }
}
